package com.sf.fy.uav.common.utils;

import java.util.HashMap;
import java.util.Map;

import javax.crypto.ShortBufferException;
import javax.naming.ConfigurationException;


import com.alibaba.fastjson.JSON;
import com.sf.encryption.machine.config.SfUserDataEncrypt;
import com.sf.encryption.machine.entity.ApplicationSecurityInfo;
import com.sf.encryption.machine.entity.DecryptedDataInfo;

import cn.tass.exceptions.TAException;
import io.micrometer.common.util.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @Auther: 01304522
 * @Date: 2022/1/12 16:19
 * 电话号码加解密工具类
 */
@Component
public class PhoneEncoderUtil {

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(PhoneEncoderUtil.class);


    @Value("${encrypt.config-env:test}")
    private String encryptConfigEnv;


    /**
     * 加密数据标识
     */
    public static final String DATAENCRYPT_PREFIX = "DE";

    /**
     * 手机号码密钥索引
     */
    public static final int TEL_INDEX = 21;

    /**
     * 电话号码解密
     *
     * @param flag          值为0，表示该次解密用于后台计算；值为1，表示该次解密用于前端脱敏展示；值为2，表示该次解密用于前端明文展示。
     * @param operateUserid 若为系统调用，传“null”字符串(不是null)
     * @param key
     * @param value         如key值不存在则整个key-value不传
     * @param phone         解密主体
     * @return
     */
    public static String decryptPhone(int flag, String operateUserid, String key, String value, String phone, SfUserDataEncrypt userDataEncrypt) {
        String phoneStr = null;
        try {
            if (StringUtils.isNotBlank(phone) && phone.startsWith(DATAENCRYPT_PREFIX)) {
                try {
                    ApplicationSecurityInfo securityInfo = new ApplicationSecurityInfo();
                    securityInfo.setDstApp("IE-UOCS-CORE");
                    securityInfo.setDstAppService("ie-uocs-core-sys");
                    securityInfo.setSrcIp(NetUtils.getLinuxIp());
                    securityInfo.setDstIpOrDomain(NetUtils.getLinuxIp());
                    if (flag == 0) {
                        securityInfo.setOperateUserid(null);
                    } else {
                        securityInfo.setOperateUserid(operateUserid);
                    }
                    securityInfo.setOperateFunction("com.sf.uocs.cof.utils.PhoneEncoderUtil.decryptPhone");
                    Map<String, Object> dataMap = new HashMap<>();
                    if (StringUtils.isNotBlank(key)) {
                        dataMap.put(key, value);
                    }
                    dataMap.put("flag", flag);
                    securityInfo.setSensitiveDataContext(JSON.toJSONString(dataMap));
                    DecryptedDataInfo decryptedDataInfo = userDataEncrypt.dataDecrypt(phone.substring(2), securityInfo);
                    phoneStr = decryptedDataInfo.getData();
                } catch (ShortBufferException e) {
                    e.printStackTrace();
                    logger.error("decryptPhone fail", e);
                } catch (TAException e) {
                    e.printStackTrace();
                    logger.error("decryptPhone fail", e);
                }
            } else {
                phoneStr = phone;
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("get decrypt fail", e);
        }
        return phoneStr;
    }

    /**
     * 电话号码加密
     *
     * @param phone
     * @return
     */
    public static String encryptPhone(String phone, SfUserDataEncrypt userDataEncrypt) {
        String phoneStr = null;
        try {
            if (StringUtils.isNotBlank(phone)) {
                try {
                    phoneStr = userDataEncrypt.dataEncrypt(21, 0x11, phone);
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("decryptPhone fail", e);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("get decrypt fail", e);
        }
        return phoneStr;
    }

    public String decryptString(String txt) {
        String conntimeout = "3000ms";
        String readtimeout = "1000ms";
        String strConfig = "";
        if ("prod".equals(encryptConfigEnv)) {
            strConfig = "{" + "[LOGGER]\n" + "logsw = info,error\n" + "logPath = ./logs\n" + "\n" + "[HOST 1]\n" + "hsmModel = VSM1310\n" + "linkNum = -2\n" + "host = des-hsm10.int.sfdc.com.cn\n" + "port = 1080\n" + "connTimeout = 2\n" + "readTimeout = 2\n" + "msgHead = SUUtVUNTLUNPUkUgzt7Iy7v6udy/2M+1zbMAAAAAAAAAQjQ0NUU2MEM2ODcxN0U1MAAAAAAAAAAAWAtvAAAAAFJDQ05HSzNTNFMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=.fZ2ZOlCMEfVi6xYWIEKgDaJF9nMo7eThs2a4ozGs4R8=\n" + "\n" + "[HOST 2]\n" + "hsmModel = VSM1310\n" + "linkNum = -2\n" + "host = des-hsm10-dr.int.sfdc.com.cn\n" + "port = 1080\n" + "connTimeout = 2\n" + "readTimeout = 2\n" + "msgHead = SUUtVUNTLUNPUkUgzt7Iy7v6udy/2M+1zbMAAAAAAAAAQjQ0NUU2MEM2ODcxN0U1MAAAAAAAAAAAWAtvAAAAAFJDQ05HSzNTNFMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=.fZ2ZOlCMEfVi6xYWIEKgDaJF9nMo7eThs2a4ozGs4R8=\n" + "\n" + "[HOST 3]\n" + "hsmModel = VSM1310\n" + "linkNum = -2\n" + "host = des-hsm11.int.sfdc.com.cn\n" + "port = 1080\n" + "connTimeout = 2\n" + "readTimeout = 2\n" + "msgHead = SUUtVUNTLUNPUkUgzt7Iy7v6udy/2M+1zbMAAAAAAAAAQjQ0NUU2MEM2ODcxN0U1MAAAAAAAAAAAWAtvAAAAAFJDQ05HSzNTNFMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=.fZ2ZOlCMEfVi6xYWIEKgDaJF9nMo7eThs2a4ozGs4R8=\n" + "\n" + "[HOST 4]\n" + "hsmModel = VSM1310\n" + "linkNum = -2\n" + "host = des-hsm11-dr.int.sfdc.com.cn\n" + "port = 1080\n" + "connTimeout = 2\n" + "readTimeout = 2\n" + "msgHead = SUUtVUNTLUNPUkUgzt7Iy7v6udy/2M+1zbMAAAAAAAAAQjQ0NUU2MEM2ODcxN0U1MAAAAAAAAAAAWAtvAAAAAFJDQ05HSzNTNFMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=.fZ2ZOlCMEfVi6xYWIEKgDaJF9nMo7eThs2a4ozGs4R8=\n" + "\n" + "[URGENT]\n" + "host = des-escape.int.sfdc.com.cn\n" + "port = 1080\n" + "conntimeout = 2\n" + "readtimeout = 2\n" + "}";
        } else {
            strConfig = "{" + "[LOGGER];" + "logsw=error;" + "logPath=./logs;" + " [URGENT] ;" + "host = des-escape.intsit.sfdc.com.cn;" + "port = 1080;" + "conntimeout = 1000ms;" + "readtimeout = 1000ms;" + "[HOST 1];" + "hsmModel=VSM1310;" + "host=10.202.77.240;" + "port=1080;" + "connTimeout=" + conntimeout + ";" + "readTimeout=" + readtimeout + ";" + "msgHead = SUUtVUNTLUNPUkUgzt7Iy7v6udy/2M+1zbMAAAAAAAAAMUU2RDQwOEIwM0VFRkZDMAAAAAAAAAAAEgZvAAAAAFJDQ05HSzNTNFM1UwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=.J9/GGXjIng4hIi6WNm0IwaiDZX9ROo76YiKKQLBfCyQ=;" + "}";

        }
        SfUserDataEncrypt userDataEncrypt = null;
        try {
            userDataEncrypt = SfUserDataEncrypt.getInstance(strConfig);
        } catch (TAException e) {
            e.printStackTrace();
        } catch (ConfigurationException e) {
            e.printStackTrace();
        }
        String ss = decryptPhone(0, null, null, null, txt, userDataEncrypt);
        return ss;
    }

    public String encryptString(String phone) {
        String conntimeout = "3000ms";
        String readtimeout = "1000ms";
        String strConfig = "";
        if ("prod".equals(encryptConfigEnv)) {
            strConfig = "{" + "[LOGGER]\n" + "logsw = info,error\n" + "logPath = ./logs\n" + "\n" + "[HOST 1]\n" + "hsmModel = VSM1310\n" + "linkNum = -2\n" + "host = des-hsm10.int.sfdc.com.cn\n" + "port = 1080\n" + "connTimeout = 2\n" + "readTimeout = 2\n" + "msgHead = SUUtVUNTLUNPUkUgzt7Iy7v6udy/2M+1zbMAAAAAAAAAQjQ0NUU2MEM2ODcxN0U1MAAAAAAAAAAAWAtvAAAAAFJDQ05HSzNTNFMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=.fZ2ZOlCMEfVi6xYWIEKgDaJF9nMo7eThs2a4ozGs4R8=\n" + "\n" + "[HOST 2]\n" + "hsmModel = VSM1310\n" + "linkNum = -2\n" + "host = des-hsm10-dr.int.sfdc.com.cn\n" + "port = 1080\n" + "connTimeout = 2\n" + "readTimeout = 2\n" + "msgHead = SUUtVUNTLUNPUkUgzt7Iy7v6udy/2M+1zbMAAAAAAAAAQjQ0NUU2MEM2ODcxN0U1MAAAAAAAAAAAWAtvAAAAAFJDQ05HSzNTNFMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=.fZ2ZOlCMEfVi6xYWIEKgDaJF9nMo7eThs2a4ozGs4R8=\n" + "\n" + "[HOST 3]\n" + "hsmModel = VSM1310\n" + "linkNum = -2\n" + "host = des-hsm11.int.sfdc.com.cn\n" + "port = 1080\n" + "connTimeout = 2\n" + "readTimeout = 2\n" + "msgHead = SUUtVUNTLUNPUkUgzt7Iy7v6udy/2M+1zbMAAAAAAAAAQjQ0NUU2MEM2ODcxN0U1MAAAAAAAAAAAWAtvAAAAAFJDQ05HSzNTNFMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=.fZ2ZOlCMEfVi6xYWIEKgDaJF9nMo7eThs2a4ozGs4R8=\n" + "\n" + "[HOST 4]\n" + "hsmModel = VSM1310\n" + "linkNum = -2\n" + "host = des-hsm11-dr.int.sfdc.com.cn\n" + "port = 1080\n" + "connTimeout = 2\n" + "readTimeout = 2\n" + "msgHead = SUUtVUNTLUNPUkUgzt7Iy7v6udy/2M+1zbMAAAAAAAAAQjQ0NUU2MEM2ODcxN0U1MAAAAAAAAAAAWAtvAAAAAFJDQ05HSzNTNFMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=.fZ2ZOlCMEfVi6xYWIEKgDaJF9nMo7eThs2a4ozGs4R8=\n" + "\n" + "[URGENT]\n" + "host = des-escape.int.sfdc.com.cn\n" + "port = 1080\n" + "conntimeout = 2\n" + "readtimeout = 2\n" + "}";
        } else {
            strConfig = "{" + "[LOGGER];" + "logsw=error;" + "logPath=./logs;" + " [URGENT] ;" + "host = des-escape.intsit.sfdc.com.cn;" + "port = 1080;" + "conntimeout = 1000ms;" + "readtimeout = 1000ms;" + "[HOST 1];" + "hsmModel=VSM1310;" + "host=10.202.77.240;" + "port=1080;" + "connTimeout=" + conntimeout + ";" + "readTimeout=" + readtimeout + ";" + "msgHead = SUUtVUNTLUNPUkUgzt7Iy7v6udy/2M+1zbMAAAAAAAAAMUU2RDQwOEIwM0VFRkZDMAAAAAAAAAAAEgZvAAAAAFJDQ05HSzNTNFM1UwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=.J9/GGXjIng4hIi6WNm0IwaiDZX9ROo76YiKKQLBfCyQ=;" + "}";
        }

        SfUserDataEncrypt userDataEncrypt = new SfUserDataEncrypt();
        try {
            userDataEncrypt = SfUserDataEncrypt.getInstance(strConfig);
        } catch (TAException e) {
            e.printStackTrace();
        } catch (ConfigurationException e) {
            e.printStackTrace();
        }
        String ss = encryptPhone(phone, userDataEncrypt);
        return ss;
    }


    /**
     * 身份证加密
     *
     * @param identifier
     * @return
     */
    public static String encryptId(String identifier, SfUserDataEncrypt userDataEncrypt) {
        String idStr = null;
        try {
            if (StringUtils.isNotBlank(identifier)) {
                try {
                    idStr = userDataEncrypt.dataEncrypt(41, 0x14, identifier);
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error("encryptId fail", e);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("get decrypt fail", e);
        }
        return idStr;
    }


    public static void main(String[] args) throws Exception {
        //String cfgPath = PhoneEncoderUtil.class.getClassLoader().getResource("dataEncrypt.cfg.ini").getFile();
        //System.out.println("cfgPath:"+cfgPath);
        String logpath = "args[0]";
        String host1 = "args[1]";
        String host2 = "args[2]";
        String conntimeout = "3000ms";
        String readtimeout = "1000ms";
        String strConfig = "{" + "[LOGGER];" + "logsw=error;" + "logPath=./logs;" + " [URGENT] ;" + "host = des-escape.intsit.sfdc.com.cn;" + "port = 1080;" + "conntimeout = 1000ms;" + "readtimeout = 1000ms;" + "[HOST 1];" + "hsmModel=VSM1310;" + "host=10.202.77.240;" + "port=1080;" + "connTimeout=" + conntimeout + ";" + "readTimeout=" + readtimeout + ";" + "msgHead = SUUtVUNTLUNPUkUgzt7Iy7v6udy/2M+1zbMAAAAAAAAAMUU2RDQwOEIwM0VFRkZDMAAAAAAAAAAAEgZvAAAAAFJDQ05HSzNTNFM1UwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=.J9/GGXjIng4hIi6WNm0IwaiDZX9ROo76YiKKQLBfCyQ=;" + "}";
        SfUserDataEncrypt userDataEncrypt = SfUserDataEncrypt.getInstance(strConfig);
        String phone = "17675768172";
//        String ss = encryptPhone(phone, userDataEncrypt);
        String ss = "DEEQAVTqi3hy1V5HvQcMJ48zkLtq4%3D";
        //String ID = "440981199402036521";
        //String ss = encryptId(ID,userDataEncrypt);

//        System.out.println("加密前:" + phone);
//        System.out.println("加密后:" + ss);
        System.out.println("解密后:" + decryptPhone(0, null, null, null, ss, userDataEncrypt));
        //System.out.println(ByteTypeUtils.bytesToHexString(enString));
        /*for (byte b : desc.getBytes()) {
            System.out.printf("%02x ",b);
        }*/
    }


    public static String desensitization(String originalPhone) {
        originalPhone = originalPhone.substring(0, 3) + "****" + originalPhone.substring(7);
        return originalPhone;
    }
}

